package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.AgeDomain;
import server.AlexaUpdate;
import server.GetPage;
import server.GetTrackIp;
import server.GooglePageRank;
import server.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;
import data.Memcache;

@SuppressWarnings("serial")
public class SearchDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		
		String name = Utils.fomatDomain(URLDecoder.decode(req.getParameter("name"),"UTF-8"));
		
		if(Utils.checkDomain(name))
		{
			DBCollection coll = Data.data("domain");
			
			DBObject domains = coll.findOne(new BasicDBObject("name",name));
			
			if(domains == null)
			{
				Random generator = new Random();
				int r = generator.nextInt(100000);
				DBObject domain = new BasicDBObject();
				domain.put("name", name);
				domain.put("update", new Date().getTime());
				domain.put("random", r);

				try {
					new GetPage(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GooglePageRank(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AgeDomain(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AlexaUpdate(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new Whois(domain);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				try {
					Thread.sleep(5000);
					coll.save(domain);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Memcache.setMemcache("last-update", domain.get("name").toString());
				
				resp.sendRedirect("/domain/"+name);
			} else {
				resp.sendRedirect("/domain/"+name);
			}
		} else {
			resp.getWriter().println("domain does not exist !");
		}
	}
}
